package com.fenxiangle.yueding.feature.home.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.fenxiangle.yueding.R;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.suozhang.framework.component.recyclerview.DividerItemDecoration;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.widget.PowerfulEditText;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SelectMapActivity extends BaseActivity implements LocationSource, AMapLocationListener, PoiSearch.OnPoiSearchListener, AMap.OnCameraChangeListener {


    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.map)
    MapView mMapView;
    @BindView(R.id.tv_address_title)
    TextView mTvAddressTitle;
    @BindView(R.id.tv_address_snippet)
    EditText mTvAddressSnippet;
    @BindView(R.id.btn_add_address)
    TextView mBtnAddAddress;
    @BindView(R.id.edt_map_search)
    PowerfulEditText edtMapSearch;
    @BindView(R.id.btn_search)
    TextView btnSearch;

    private AMap aMap;

    private AMapLocationClient mLocationClient;

    private LatLonPoint mSearchLatLngPoint;
    private boolean isInputKeySearch;

    private boolean isItemClickAction;

    private GeocodeSearch mGeocoderSearch;

    private boolean isFirstInput = true;

    private String mSearchType = "";
    private String mSearchKey = "";
    private Marker mLocationMarker;
    private OnLocationChangedListener mOnLocationChangedListener;
    private AMapLocationClientOption mLocationOption;
    PoiItem mPoiItem = null;

    private String mCode="";

    @Override
    protected int attachLayoutRes() {

        return R.layout.activity_select_map;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
    }

    @Override
    protected void initView() {
        initToolBar(mToolbar, "定位", true, true);
        initMap();
        initLocationClient();
    }

    @Override
    protected void initData() {

    }


    private void initLocationClient() {
        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听，这里要实现AMapLocationListener接口，AMapLocationListener接口只有onLocationChanged方法可以实现，用于接收异步返回的定位结果，参数是AMapLocation类型。
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2 * 1000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
//        mStartTime = System.currentTimeMillis();
    }


    /**
     * 初始化AMap对象
     */
    private void initMap() {

        mGeocoderSearch = new GeocodeSearch(this);
        mGeocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int rCode) {

                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                    doSearchQuery();
                } else {
                    showMsg("获取地理位置失败");
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {

            }
        });

        aMap = mMapView.getMap();
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.moveCamera(CameraUpdateFactory.zoomTo(14));
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (!isItemClickAction && !isInputKeySearch) {
                    geoAddress();
                    startJumpAnimation();
                }
                mSearchLatLngPoint = new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude);
                isInputKeySearch = false;
                isItemClickAction = false;
            }
        });

        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                addMarkerInScreenCenter();
            }
        });
    }


    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        if (mMapView != null) {
            mMapView.onResume();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        if (mMapView != null) {
            mMapView.onPause();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mMapView != null) {
            mMapView.onSaveInstanceState(outState);
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMapView != null) {
            mMapView.onDestroy();

        }
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();//销毁定位客户端。
        }
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mOnLocationChangedListener = onLocationChangedListener;
    }


    @Override
    public void deactivate() {
        mOnLocationChangedListener = null;
        //设置定位监听 停用
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

        if (mOnLocationChangedListener != null && aMapLocation != null && aMapLocation.getErrorCode() == 0) {

            mOnLocationChangedListener.onLocationChanged(aMapLocation);

            LatLng curLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());

            mSearchLatLngPoint = new LatLonPoint(curLatLng.latitude, curLatLng.longitude);

            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatLng, 16f));

            isInputKeySearch = false;

            // mActKeyword.setText("");

            mCode=aMapLocation.getCityCode();

        } else {
            showMsg("定位失败" + aMapLocation);
        }
    }


    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (i == 1000) {

        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }


    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
 
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    /**
     * 响应逆地理编码
     */
    public void geoAddress() {
        // mActKeyword.setText("");
        if (mSearchLatLngPoint != null) {
//            showLoading();
            RegeocodeQuery query = new RegeocodeQuery(mSearchLatLngPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
            mGeocoderSearch.getFromLocationAsyn(query);
        }
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {
//        showMsg(mCode);
        PoiSearch.Query query = new PoiSearch.Query(mSearchKey, mSearchType, mCode);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setCityLimit(true);
        query.setPageSize(400);
        query.setCityLimit(true);
        query.setPageNum(0);

        if (mSearchLatLngPoint != null) {
            PoiSearch poiSearch = new PoiSearch(this, query);
            poiSearch.setBound(new PoiSearch.SearchBound(mSearchLatLngPoint, 1000, true));
            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                @Override
                public void onPoiSearched(PoiResult poiResult, int resultCode) {

                    List<PoiItem> poiItems = poiResult == null ? null : poiResult.getPois();
                    if (poiItems == null || poiItems.isEmpty()) {
                        showMsg("没有周边搜索结果，请切换搜索类型或重新选择位置");
                    } else {
                        mPoiItem = poiItems.get(0);
                        mTvAddressTitle.setText(mPoiItem.getTitle());
                        mTvAddressSnippet.setText(mPoiItem.getSnippet());
                    }
//

                }

                @Override
                public void onPoiItemSearched(PoiItem poiItem, int i) {

                }
            });
            poiSearch.searchPOIAsyn();
        }
    }

    private void addMarkerInScreenCenter() {
        LatLng latLng = aMap.getCameraPosition().target;
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        mLocationMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
        //设置Marker在屏幕上,不跟随地图移动
        mLocationMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        mLocationMarker.setZIndex(1);
    }

    /**
     * 屏幕中心marker 跳动
     */
    public void startJumpAnimation() {
        if (mLocationMarker != null) {
            //根据屏幕距离计算需要移动的目标点
            final LatLng latLng = mLocationMarker.getPosition();
            Point point = aMap.getProjection().toScreenLocation(latLng);
            point.y -= DensityUtil.dp2px(125);
            LatLng target = aMap.getProjection()
                    .fromScreenLocation(point);
            //使用TranslateAnimation,填写一个需要移动的目标点
            Animation animation = new TranslateAnimation(target);
            animation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    // 模拟重加速度的interpolator
                    if (input <= 0.5) {
                        return (float) (0.5f - 2 * (0.5 - input) * (0.5 - input));
                    } else {
                        return (float) (0.5f - Math.sqrt((input - 0.5f) * (1.5f - input)));
                    }
                }
            });
            //整个移动所需要的时间
            animation.setDuration(600);
            //设置动画
            mLocationMarker.setAnimation(animation);
            //开始动画
            mLocationMarker.startAnimation();

        } else {
            Log.d("", "没有标记位置，不能跳转");
        }
    }


    /**
     * 更新poi搜索结果
     *
     * @param poiItems
     */
    private void updatePoiResult(List<PoiItem> poiItems) {
//        mPoiResultAdapter.setNewData(poiItems);
//        mPoiResultAdapter.setSelectedPosition(0);
    }


    @OnClick({R.id.btn_search, R.id.btn_add_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_search:
                if (TextUtils.isEmpty(edtMapSearch.getText().toString())){
                    showMsg("请输入搜索关键词！");
                    return;
                }
                doSearchQPopup(edtMapSearch.getText().toString(),view);
                break;
            case R.id.btn_add_address:
                Intent intent = new Intent();
                intent.putExtra("poi_item", mPoiItem);
                setResult(2, intent);
                finish(); //结束当前的activity的生命周期
                break;
        }
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQPopup(String key,View view) {
        PoiSearch.Query query = new PoiSearch.Query(key, mSearchType, mCode);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，
        // 第三个参数表示poi搜索区域（空字符串代表全国）
        query.setCityLimit(true);
        query.setPageSize(200);
        query.setPageNum(0);

        if (mSearchLatLngPoint != null) {
            PoiSearch poiSearch = new PoiSearch(this, query);
//            poiSearch.setBound(new PoiSearch.SearchBound(mSearchLatLngPoint, 1000, true));
            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void onPoiSearched(PoiResult poiResult, int resultCode) {

                    List<PoiItem> poiItems = poiResult == null ? null : poiResult.getPois();
                    if (poiItems == null || poiItems.isEmpty()) {
                        showMsg("没有周边搜索结果，请切换搜索类型或重新选择位置");
                    } else {
                      initPopup(view,poiItems,SelectMapActivity.this);
                    }
//

                }

                @Override
                public void onPoiItemSearched(PoiItem poiItem, int i) {

                }
            });
            poiSearch.searchPOIAsyn();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private  void initPopup(View view, List<PoiItem> poiItems, Context context){
        // 用于PopupWindow的View
        View contentView= LayoutInflater.from(context).inflate(R.layout.popup_location, null, false);
        // 创建PopupWindow对象，其中：
        // 第一个参数是用于PopupWindow中的View，第二个参数是PopupWindow的宽度，
        // 第三个参数是PopupWindow的高度，第四个参数指定PopupWindow能否获得焦点

        RecyclerView recyclerView=contentView.findViewById(R.id.rv_location);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(new DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(2));
        LocationAdapter locationAdapter=new LocationAdapter();
        locationAdapter.bindToRecyclerView(recyclerView);
        locationAdapter.setNewData(poiItems);
        locationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("poi_item", poiItems.get(position));
                setResult(2, intent);
                finish(); //结束当前的activity的生命周期
            }
        });
        int w = getWindowManager().getDefaultDisplay().getWidth();
        PopupWindow window=new PopupWindow(contentView, w-100,
                LinearLayout.LayoutParams.WRAP_CONTENT, true);

        // 设置PopupWindow的背景
        window.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_map_text));
        // 设置PopupWindow是否能响应外部点击事件
        window.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        window.setTouchable(true);
        // 显示PopupWindow，其中：
        // 第一个参数是PopupWindow的锚点，第二和第三个参数分别是PopupWindow相对锚点的x、y偏移
        window.showAsDropDown(view, 0, 70, Gravity.CENTER_HORIZONTAL);
        // 或者也可以调用此方法显示PopupWindow，其中：
        // 第一个参数是PopupWindow的父View，第二个参数是PopupWindow相对父View的位置，
        // 第三和第四个参数分别是PopupWindow相对父View的x、y偏移
        // window.showAtLocation(parent, gravity, x, y);
    }


    class LocationAdapter extends BaseQuickAdapter<PoiItem,BaseViewHolder> {
        public LocationAdapter() {
            super(R.layout.item_popup_location);
        }

        @Override
        protected void convert(BaseViewHolder helper, PoiItem item) {
          helper.setText(R.id.tv_popup_address,item.getTitle());
        }
    }
}
